package pres.man.interview.producerconsumer.monitors;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 管程实现
 *
 * @author MAN
 * @date 2020-12-08 21:38
 * @project
 * @since
 */
public class Monitors {
    private int count;

    public synchronized void add() {
        if(count == 5){
            System.out.println("count等于5了不能再加了");
            return;
        }
        System.out.println("当前 count " + ++count);
    }

    public synchronized void de() {
        if(count == 0){
            System.out.println("count等于0了不能再减了");
            return;
        }
        System.out.println("当前 count " + --count);
    }

    private static final ThreadPoolExecutor POOL = new ThreadPoolExecutor(5, 8, 20, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10), new ThreadPoolExecutor.CallerRunsPolicy());

    public static void main(String[] args) {
        Monitors monitors = new Monitors();

        POOL.execute(() -> {
            for (; ; ) {
                monitors.add();
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        POOL.execute(() -> {
            for (; ; ) {
                monitors.add();
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        POOL.execute(() -> {
            for (; ; ) {
                monitors.add();
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        POOL.execute(() -> {
            for (; ; ) {
                monitors.de();
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
